import Vue from 'vue';
import VueRouter from "vue-router";

import routes from './routes';
import store from "@/store"

Vue.use(VueRouter)
//对编程式路由导航路由重复报错问题的解决
const originalPush= VueRouter.prototype.push
const originalReplace= VueRouter.prototype.replace

VueRouter.prototype.push=function(location,okCallback,errorCallback){
    if(okCallback===undefined&&errorCallback===undefined){
        originalPush.call(this,location).catch(()=>{});
    }else{
        originalPush.call(this,location,okCallback,errorCallback)
    }
}
VueRouter.prototype.replace=function(location,okCallback,errorCallback){
    if(okCallback===undefined&&errorCallback===undefined){
        originalReplace.call(this,location).catch(()=>{});
    }else{
        originalReplace.call(this,location,okCallback,errorCallback)
    }
}

const router =new VueRouter({
    mode:'history',
    routes,
    scrollBehavior (to, from, savedPosition) {
        if(savedPosition){
            return savedPosition
        }
        return {x:0,y:0}
    }
});
//路由守卫
//全局前置路由守卫
router.beforeEach(async (to, from, next) => {
    const {userToken,userInfo}=store.state.user
    if(userToken){
        if(userInfo.id){
            next()
        }else{
            try {
                await store.dispatch('user/getUserInfo')
                next()
            } catch (error) {
                await store.dispatch('user/userLogout')
                next('/login')
            }
        }
    }else{
        const pathList=['/pay','/paysuccess','/trade']
        if(pathList.some(path=>to.path===path)){
            next('/login')
        }else{
            next()
        }
    }
  })
  export default router